#include "piece.h"
#include "ui_piece.h"

Piece::Piece(QWidget *parent, QString m_nomPiece, int m_IDPiece, QSqlDatabase instBDD) :
    QWidget(parent),
    ui(new Ui::Piece)
{
    ui->setupUi(this);

    nomPiece = m_nomPiece;
    IDPiece = m_IDPiece;
    bdd = QSqlDatabase::cloneDatabase(instBDD, "instancePiece" + IDPiece);

    if(!bdd.open())
    {
        qDebug() << bdd.lastError().text();
    }

    ui->nomPiece->setText(nomPiece);

    MAJEquipement();
}

Piece::~Piece()
{
    delete ui;
}

void Piece::MAJEquipement()
{
    for(int i=0; i<listeEquipement.size(); ++i)
    {
        delete listeEquipement.at(i);
    }

    listeEquipement.clear();

    QSqlQuery recupChauffage(bdd);

    recupChauffage.prepare("SELECT ID_Chauffage, Etat, Temperature, TemperatureMax, TemperatureMin FROM Chauffage WHERE ID_Piece = ?");
    recupChauffage.addBindValue(IDPiece);

    if(recupChauffage.exec())
    {
        while (recupChauffage.next())
        {
            listeEquipement.append(new Chauffage(this, recupChauffage.value(0).toInt(), recupChauffage.value(1).toBool(), recupChauffage.value(2).toFloat(), recupChauffage.value(3).toFloat(), recupChauffage.value(4).toFloat()));
        }
    }
    else
    {
        qDebug() << recupChauffage.lastError().text();
    }

    for(int i=0; i<listeEquipement.size(); ++i)
    {
        ui->verticalLayout->addWidget(listeEquipement.at(i));
    }
}

QString Piece::getNom() const
{
    return nomPiece;
}
